<!-- 单词管理页面 -->
<template>
    <div style="padding: 20px 39px;">
        <el-input 
        type="text"
        placeholder="请输入关键词"
        v-model.trim="seaTxt"
         />
         
    </div>
    <div id="tbdiv">
      <el-table 
    ref="tbObj"
    :data="result" 
    style="width: 100%"
    @selection-change="sel"
    >
    <el-table-column type="selection" />
    <el-table-column prop="id" label="id"  />
    <el-table-column prop="chinese" label="中文"  />
    <el-table-column prop="english" label="英文"  />
    <el-table-column prop="author" label="发布者"  />
    <el-table-column prop="createdAt" label="发布时间"  />
    <el-table-column prop="updatedAt" label="更新时间"  />
    <el-table-column label="处理">
      <template #default="scope">
        <el-button 
        size="small" 
        @click="editWord(scope.row.id)"
          >编辑</el-button
        >
        <el-button
          size="small"
          type="danger"
          @click="delWord(scope.row.id)"
          >删除</el-button
        >
      </template>
    </el-table-column>
    
  </el-table>
    </div>
  
  <div class="pageMange">
    <el-pagination
    background  
    :page-size="10"
    layout="prev, pager, next"
    :page-count="Math.ceil(arrBySeaTxt.length/10)"
    v-model:current-page="cpg"
  />  
  
  <el-button type="danger" @click="delWordList" style="float: right;margin-right: 5 vw;">删除</el-button>
  
  </div>


  
  <el-dialog
    v-model="isEdit"
    title="请输入新数据"
    width="30%"
  >
    <div id="editkj">
      <p>
        <el-text type="primary">id: </el-text> 
        <el-text> {{ editData.id }}</el-text>
      </p>
      <p style="margin: 10px auto;">
        <el-text type="primary">中文: </el-text> 
        <el-input v-model="editData.chinese"></el-input>
      </p>
      <p>
        <el-text type="primary">英文: </el-text> 
        <el-input v-model="editData.english"></el-input>
      </p>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="isEdit = false">取消</el-button>
        <el-button type="primary" @click="editPut">
          确认修改
        </el-button>
      </span>
    </template>
  </el-dialog>
 
</template>
<script setup>
    import { ref,reactive,computed,onMounted,toRaw } from 'vue'
    import { ElMessage } from 'element-plus'
    import axios from '../../config/axios'
    
    let tbObj = ref(null);
    let cpg = ref(1);
    let wordArr = reactive([
        {id:'1s',chinese:'管理',english:'manage',author:'曾曾',createdAt:'2022-12-12',updatedAt:'2022-12-12'},
    ])
    let userArr = reactive([]);
    let isEdit = ref(false);
   
    let editData = reactive({
      id:0,
      chinese:'',
      english:''
    }) 
    let filterOpt = reactive({
      beginTime:'',
      endTime:'',
      author:'',
      str:''
    })
    
    
    let arrBySeaTxt = computed(()=>{
      let arr = wordArr.map(e=>{
        e.createdAt = new Date(e.createdAt).toLocaleDateString();
        e.updatedAt = new Date(e.updatedAt).toLocaleDateString();
        userArr.forEach(se=>{
          if(se.id == e.authorId){
            e.author = se.username;
          }
        })
        return e;
      })
      
      arr = arr.filter(
        e=>(e.id+"").includes(filterOpt.str) ||
        e.chinese.includes(filterOpt.str) ||
        e.english.includes(filterOpt.str) ||
        e.author+"".includes(filterOpt.str)
      )
     
      return arr
    })
    function editWord(id){
      isEdit.value = true;
      wordArr.filter(e=>{
        if(e.id == id){
          editData.id = e.id;
          editData.chinese = e.chinese;
          editData.english = e.english;
        }
      })
    }
    function editPut(){
      axios.put('/word',{
        id:editData.id,
        chinese:editData.chinese,
        english:editData.english,
      }).then(res=>{
        if(res.data.result){
          ElMessage.success('修改成功');
          isEdit.value = false;
          getAllWord();
        }else{
          ElMessage.error('修改失败');
          console.log(res.data);
        }
      }).catch(err=>{
          ElMessage.error('修改失败');
          console.log(err);
      })
    }


    

    let result = computed(()=>{
      let arr = [];
      //分页过滤
      for(let i = 0;i<10;i++){
        if(arrBySeaTxt.value[i+((cpg.value-1)*10)])arr[i] = arrBySeaTxt.value[i+((cpg.value-1)*10)];
      }
      return arr  
    })
   
    
    let selData = [];
    function sel(data){
        selData = data;
    }
    
    function getAllWord(){
        axios.get('/word').then(res=>{
            if(res.data.result){
                ElMessage.success(`一共获取到${res.data.data.length}个词组`)
                wordArr.splice(0,wordArr.length,...res.data.data);
            }else{
                ElMessage.warning(res.data.msg);
                if(res.data.msg == 'token过期了'){
                    router.push('/login');
                }
            }
        })
    }

    function getAllUser(){
      axios.get('/user').then(res=>{
            if(res.data.result){
                userArr.splice(0,userArr.length,...res.data.data);
            }else{
                ElMessage.warning('用户信息请求失败');
            }
        })
    }

    async function delWord(id){
      await axios.delete('/word/'+id).then(res=>{
            if (res.data.result) {
                ElMessage.success('删除成功');
                getAllWord();
            }else{
                ElMessage.warning('删除失败')
                console.log(res.data);
            }
        }).catch(err=>{
            ElMessage.warning('服务器异常')
            console.log(err);
        })
    }

    async function delWordList(){
      if (!confirm('你确定要删除'+selData.length+'条数据吗？')) return;
      for (let i = 0;i<selData.length;i++) {
        await delWord(selData[i].id);
      }
    }

    onMounted(()=>{
      getAllUser();
      getAllWord();
    })

    

</script>

<style>
.dialog-footer button:first-child {
  margin-right: 10px;
}
.pageMange{
  position: fixed;
  bottom: 40px;
  width: 100vw;
}
#tbdiv{
  height: calc(100vh - 280px);
  overflow-y: auto;
}
</style>
